<template>
  <div class="design-editor-full-page">
    <!-- Top tab navigation -->
    <EditorTabs 
      :activeTab="activeTab" 
      @tabChange="switchTab" 
      @save="saveDesign" 
      @export="exportDesign"
    />
    
    <!-- Main Content Area -->
    <div class="editor-main">
      <!-- Left Sidebar -->
      <div class="editor-sidebar" :class="{ 'collapsed': leftSidebarCollapsed, 'hidden': !showSidebar }">
        <!-- 模版标签内容 -->
        <TemplatePanel 
          v-if="activeTab === 'template'" 
          :designTemplates="designTemplates"
          @applyDesignTemplate="applyDesignTemplate"
          @applyTemplate="applyTemplate"
          @createBlankCanvas="createBlankCanvas"
          @createCustomCanvas="createCustomCanvas"
        />
        
        <!-- 文字标签内容 -->
        <TextPanel 
          v-if="activeTab === 'text'" 
          :fontFamily="defaultFontFamily"
          :textColor="defaultTextColor"
          @addHeading="type => addNewText(type)"
          @addSubheading="type => addNewText(type)"
          @addParagraph="type => addNewText(type)"
          @applyTextStyle="applyTextStyle"
          @fontFamilyChange="val => defaultFontFamily = val"
          @colorChange="setColor"
          @applyTemplate="applyTemplate"
        />
        
        <!-- 素材标签内容 -->
        <MaterialPanel 
          v-if="activeTab === 'material'" 
          :materials="materials"
          :backgroundType="backgroundType"
          :backgroundColor="backgroundColor"
          @addRectangle="addNewRect"
          @addCircle="addNewCircle"
          @addTriangle="addTriangle"
          @addPolygon="addPolygon"
          @drawLine="drawLine"
          @addMaterial="addMaterial"
          @imageUpload="handleImageUpload"
          @backgroundTypeChange="val => backgroundType = val"
          @backgroundColorChange="setBackgroundColor"
        />
        
        <!-- 预览标签内容 -->
        <PreviewPanel 
          v-if="activeTab === 'preview'" 
          :previewDevice="previewDevice"
          :deviceDimensions="getPreviewDimensions()"
          :exportFormat="exportFormat"
          :exportQuality="exportQuality"
          :exportWidth="exportWidth"
          :exportHeight="exportHeight"
          :maintainAspectRatio="maintainAspectRatio"
          @deviceChange="val => previewDevice = val"
          @formatChange="val => exportFormat = val"
          @qualityChange="val => exportQuality = parseInt(val)"
          @dimensionChange="handleDimensionChange"
          @ratioChange="val => maintainAspectRatio = val"
          @openPreview="previewDesign"
          @exportDesign="exportDesign"
        />

        <!-- 图层面板内容 -->
        <LayerPanel
          v-if="activeTab === 'layer'"
          :layers="layers"
          :activeLayerId="activeLayerId"
          @add-layer="addLayer"
          @delete-layer="deleteLayer"
          @select-layer="selectLayer"
          @toggle-visibility="toggleLayerVisibility"
          @toggle-lock="toggleLayerLock"
        />
        
        <!-- 侧边栏收缩按钮 -->
        <div class="sidebar-collapse-button" @click="toggleLeftSidebar">
          {{ leftSidebarCollapsed ? '›' : '‹' }}
        </div>
      </div>
      
      <!-- Center Canvas Area -->
      <div class="editor-canvas-area">
        <!-- 顶部工具栏 -->
        <div class="editor-toolbar">
          <!-- 基础操作组 -->
          <div class="toolbar-group">
            <button class="toolbar-btn" title="选择 (V)" @click="setMode('select')">
              <i class="fas fa-mouse-pointer"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn" title="剪切 (Ctrl+X)" @click="cutObject">
              <i class="fas fa-cut"></i>
            </button>
            <button class="toolbar-btn" title="复制 (Ctrl+C)" @click="copyObject">
              <i class="fas fa-copy"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn danger" title="删除 (Delete)" @click="deleteObject">
              <i class="fas fa-trash-alt"></i>
            </button>
          </div>

          <div class="group-separator"></div>

          <!-- 对齐操作组 -->
          <div class="toolbar-group">
            <button class="toolbar-btn" title="左对齐" @click="alignObjects('left')">
              <i class="fas fa-align-left"></i>
            </button>
            <button class="toolbar-btn" title="水平居中" @click="alignObjects('center')">
              <i class="fas fa-align-center"></i>
            </button>
            <button class="toolbar-btn" title="右对齐" @click="alignObjects('right')">
              <i class="fas fa-align-right"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn" title="顶部对齐" @click="alignObjects('top')">
              <i class="fas fa-grip-lines"></i>
            </button>
            <button class="toolbar-btn" title="垂直居中" @click="alignObjects('middle')">
              <i class="fas fa-grip-lines" style="transform: translateY(2px);"></i>
            </button>
            <button class="toolbar-btn" title="底部对齐" @click="alignObjects('bottom')">
              <i class="fas fa-grip-lines" style="transform: translateY(4px);"></i>
            </button>
          </div>

          <div class="group-separator"></div>

          <!-- 分布操作组 -->
          <div class="toolbar-group">
            <button class="toolbar-btn" title="水平分布" @click="distributeObjects('horizontal')">
              <i class="fas fa-ellipsis-h"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn" title="垂直分布" @click="distributeObjects('vertical')">
              <i class="fas fa-ellipsis-v"></i>
            </button>
          </div>

          <div class="group-separator"></div>

          <!-- 图层操作组 -->
          <div class="toolbar-group">
            <button class="toolbar-btn" title="置于顶层" @click="arrangeLayer('front')">
              <i class="fas fa-layer-group"></i>
            </button>
            <button class="toolbar-btn" title="上移一层" @click="arrangeLayer('forward')">
              <i class="fas fa-chevron-up"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn" title="下移一层" @click="arrangeLayer('backward')">
              <i class="fas fa-chevron-down"></i>
            </button>
            <button class="toolbar-btn" title="置于底层" @click="arrangeLayer('back')">
              <i class="fas fa-layer-group" style="opacity: 0.5;"></i>
            </button>
          </div>

          <div class="group-separator"></div>

          <!-- 对象操作组 -->
          <div class="toolbar-group">
            <button class="toolbar-btn" title="锁定/解锁 (Ctrl+L)" @click="toggleLock">
              <i class="fas" :class="[selectedObject?.lockMovementX ? 'fa-lock' : 'fa-lock-open']"></i>
            </button>
            <button class="toolbar-btn" title="组合/解组 (Ctrl+G)" @click="toggleGroup">
              <i class="fas" :class="[selectedObject?.type === 'group' ? 'fa-object-ungroup' : 'fa-object-group']"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn" title="水平翻转" @click="flipObject('horizontal')">
              <i class="fas fa-arrows-alt-h"></i>
            </button>
            <button class="toolbar-btn" title="垂直翻转" @click="flipObject('vertical')">
              <i class="fas fa-arrows-alt-v"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn" title="克隆 (Ctrl+D)" @click="cloneObject">
              <i class="far fa-clone"></i>
            </button>
          </div>

          <div class="group-separator"></div>

          <!-- 辅助工具组 -->
          <div class="toolbar-group">
            <button class="toolbar-btn" :class="{ active: showGrid }" title="显示网格" @click="toggleGrid">
              <i class="fas fa-border-all"></i>
            </button>
            <button class="toolbar-btn" :class="{ active: showRuler }" title="显示标尺" @click="toggleRuler">
              <i class="fas fa-ruler-combined"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn" title="显示参考线" @click="showGuidelines(selectedObject)">
              <i class="fas fa-grip-lines"></i>
            </button>
            <button class="toolbar-btn" title="显示尺寸" @click="showDimensions(selectedObject)">
              <i class="fas fa-ruler"></i>
            </button>
          </div>

          <div class="group-separator"></div>

          <!-- 缩放控制组 -->
          <div class="toolbar-group">
            <button class="toolbar-btn" title="缩小 (Ctrl+-)" @click="zoomOut">
              <i class="fas fa-search-minus"></i>
            </button>
            <div class="zoom-level">{{ Math.round(zoomLevel * 100) }}%</div>
            <button class="toolbar-btn" title="放大 (Ctrl++)" @click="zoomIn">
              <i class="fas fa-search-plus"></i>
            </button>
            <div class="toolbar-separator"></div>
            <button class="toolbar-btn" title="重置缩放 (Ctrl+0)" @click="originalSize">
              <i class="fas fa-expand"></i>
            </button>
          </div>
        </div>
        
        <!-- Canvas工作区 -->
        <div class="canvas-wrapper">
          <div id="canvas-container" class="canvas-box">
            <canvas id="fabric-canvas"></canvas>
          </div>
          <!-- 调试信息 -->
          <div id="debug-info" class="debug-info">
            Canvas状态: {{ initialized ? '初始化成功' : '未初始化' }}
          </div>
        </div>
      </div>
      
      <!-- Right Properties Panel -->
      <div class="editor-properties" :class="{ 'collapsed': rightSidebarCollapsed }">
        <div class="properties-tabs">
          <div 
            class="property-tab" 
            :class="{ active: propertiesTab === 'properties' }"
            @click="propertiesTab = 'properties'"
          >
            属性
          </div>
          <div 
            class="property-tab"
            :class="{ active: propertiesTab === 'text2img' }"
            @click="propertiesTab = 'text2img'"
          >
            文生图
          </div>
          <div 
            class="property-tab"
            :class="{ active: propertiesTab === 'img2img' }"
            @click="propertiesTab = 'img2img'"
          >
            图生图
          </div>
        </div>
        
        <div class="properties-content">
          <!-- 属性标签页内容 -->
          <div v-if="propertiesTab === 'properties'">
            <!-- Object Properties -->
            <div v-if="selectedObject" class="property-section">
              <h3>对象属性</h3>
              
              <div class="property-group">
                <h4>位置与大小</h4>
                
                <div class="property-row">
                  <label>X:</label>
                  <input type="number" v-model="selectedObjectProps.left" @change="updateObjectProperty('left')">
                  <label>Y:</label>
                  <input type="number" v-model="selectedObjectProps.top" @change="updateObjectProperty('top')">
                </div>
                
                <div class="property-row">
                  <label>宽:</label>
                  <input type="number" v-model="selectedObjectProps.width" @change="updateObjectProperty('width')">
                  <label>高:</label>
                  <input type="number" v-model="selectedObjectProps.height" @change="updateObjectProperty('height')">
                </div>
                
                <div class="property-row">
                  <label>旋转:</label>
                  <input type="range" min="0" max="360" v-model="selectedObjectProps.angle" @change="updateObjectProperty('angle')">
                  <span>{{ selectedObjectProps.angle }}°</span>
                </div>
              </div>
              
              <div class="property-group">
                <h4>外观</h4>
                
                <div class="property-row">
                  <label>填充:</label>
                  <input 
                    type="color" 
                    v-model="selectedObjectProps.fill" 
                    @change="updateObjectProperty('fill')"
                  >
                </div>
                
                <div class="property-row">
                  <label>描边:</label>
                  <input 
                    type="color" 
                    v-model="selectedObjectProps.stroke" 
                    @change="updateObjectProperty('stroke')"
                  >
                  <label>宽度:</label>
                  <input 
                    type="number" 
                    min="0" 
                    max="20" 
                    v-model="selectedObjectProps.strokeWidth" 
                    @change="updateObjectProperty('strokeWidth')"
                  >
                </div>
                
                <div class="property-row">
                  <label>不透明度:</label>
                  <input type="range" min="0" max="1" step="0.01" v-model="selectedObjectProps.opacity" @change="updateObjectProperty('opacity')">
                  <span>{{ Math.round(selectedObjectProps.opacity * 100) }}%</span>
                </div>
              </div>
              
              <!-- Text specific properties -->
              <div v-if="isTextObject" class="property-group">
                <h4>文字属性</h4>
                
                <div class="property-row">
                  <label>文字:</label>
                  <textarea v-model="selectedObjectProps.text" @change="updateObjectProperty('text')"></textarea>
                </div>
                
                <div class="property-row">
                  <label>字体:</label>
                  <select v-model="selectedObjectProps.fontFamily" @change="updateObjectProperty('fontFamily')">
                    <option value="Arial">Arial</option>
                    <option value="Times New Roman">Times New Roman</option>
                    <option value="微软雅黑">微软雅黑</option>
                    <option value="宋体">宋体</option>
                    <option value="黑体">黑体</option>
                    <option value="楷体">楷体</option>
                  </select>
                </div>
                
                <div class="property-row">
                  <label>字号:</label>
                  <input type="number" min="8" max="120" v-model="selectedObjectProps.fontSize" @change="updateObjectProperty('fontSize')">
                </div>
                
                <div class="property-row">
                  <button class="style-button" @click="toggleBold">
                    <span class="font-bold">B</span>
                  </button>
                  <button class="style-button" @click="toggleItalic">
                    <span class="font-italic">I</span>
                  </button>
                  <button class="style-button" @click="toggleUnderline">
                    <span class="font-underline">U</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 侧边栏收缩按钮 -->
        <div class="sidebar-collapse-button right" @click="toggleRightSidebar">
          {{ rightSidebarCollapsed ? '‹' : '›' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 导入组件
import EditorTabs from '../components/editor/EditorTabs.vue';
import TemplatePanel from '../components/editor/TemplatePanel.vue';
import TextPanel from '../components/editor/TextPanel.vue';
import MaterialPanel from '../components/editor/MaterialPanel.vue';
import PreviewPanel from '../components/editor/PreviewPanel.vue';
import LayerPanel from '../components/editor/LayerPanel.vue';

// 导入服务
import * as fabricModule from 'fabric';
const fabric = fabricModule.fabric || fabricModule;
// import { imageEditorService } from '../services/image-editor.service';
import { fileToDataURL } from '../services/utils/imageUtils';

export default {
  name: 'SimpleEditorView',
  components: {
    EditorTabs,
    TemplatePanel,
    TextPanel,
    MaterialPanel,
    PreviewPanel,
    LayerPanel
  },
  data() {
    return {
      // 编辑器服务实例
      editorService: null,
      canvas: null,
      initialized: false, // 初始化状态标记

      // 导航标签
      activeTab: 'template',
      propertiesTab: 'properties',
      
      // 侧边栏状态
      leftSidebarCollapsed: false,
      rightSidebarCollapsed: false,
      showSidebar: true,  // 控制侧边栏显示/隐藏

      // 工作区设置
      workspaceWidth: 800,
      workspaceHeight: 600,
      workspaceBackground: '#ffffff',
      zoomLevel: 1,
      
      // 编辑器状态
      selectedObject: null,
      selectedObjectProps: {},
      
      // 文字设置
      defaultFontFamily: 'Arial',
      defaultTextColor: '#333333',
      
      // 形状设置
      defaultShapeFill: '#3498db',
      defaultShapeStroke: '#2980b9',
      
      // 背景设置
      backgroundType: 'color',
      backgroundColor: '#ffffff',
      
      // 预览设置
      previewDevice: 'desktop',
      showGrid: false,
      showRuler: false,
      
      // 导出设置
      exportFormat: 'png',
      exportQuality: 90,
      exportWidth: 800,
      exportHeight: 600,
      maintainAspectRatio: true,
      
      // 模板数据
      designTemplates: [
        {
          id: 'template_1',
          name: '商业海报',
          category: 'poster',
          thumbnail: 'https://picsum.photos/id/1/200/300',
          width: 800,
          height: 1200,
          description: '适用于各类商业宣传海报设计',
          elements: [
            {
              type: 'text',
              text: '商业海报标题',
              fontSize: 48,
              fontWeight: 'bold',
              left: 400,
              top: 100,
              textAlign: 'center',
              fill: '#333333'
            },
            {
              type: 'text',
              text: '副标题文本',
              fontSize: 24,
              left: 400,
              top: 200,
              textAlign: 'center',
              fill: '#666666'
            },
            {
              type: 'rect',
              left: 300,
              top: 400,
              width: 200,
              height: 200,
              fill: '#f0f0f0',
              stroke: '#dddddd'
            }
          ],
          background: {
            type: 'color',
            value: '#ffffff'
          }
        },
        {
          id: 'template_2',
          name: '社交媒体帖子',
          category: 'social',
          thumbnail: 'https://picsum.photos/id/2/200/300',
          width: 1080,
          height: 1080,
          description: '适用于Instagram等社交媒体平台',
          elements: [
            {
              type: 'image',
              src: 'https://picsum.photos/id/3/800/800',
              left: 540,
              top: 540,
              width: 800,
              height: 800
            },
            {
              type: 'text',
              text: '社交媒体标题',
              fontSize: 36,
              left: 540,
              top: 100,
              textAlign: 'center',
              fill: '#ffffff',
              shadow: {
                color: 'rgba(0,0,0,0.3)',
                blur: 10,
                offsetX: 5,
                offsetY: 5
              }
            }
          ],
          background: {
            type: 'gradient',
            value: {
              colorStops: [
                { offset: 0, color: '#1890ff' },
                { offset: 1, color: '#f759ab' }
              ]
            }
          }
        },
        {
          id: 'template_3',
          name: '简历模板',
          category: 'document',
          thumbnail: 'https://picsum.photos/id/4/200/300',
          width: 595,
          height: 842,
          description: 'A4尺寸的个人简历模板',
          elements: [
            {
              type: 'text',
              text: '个人简历',
              fontSize: 32,
              fontWeight: 'bold',
              left: 297,
              top: 50,
              textAlign: 'center',
              fill: '#333333'
            },
            {
              type: 'line',
              points: [50, 100, 545, 100],
              stroke: '#333333',
              strokeWidth: 2
            }
          ],
          background: {
            type: 'color',
            value: '#ffffff'
          }
        }
      ],
      
      // 素材数据
      materials: [
        {
          name: '抽象背景1',
          url: 'https://picsum.photos/id/10/200/200',
          type: 'image'
        },
        {
          name: '抽象背景2',
          url: 'https://picsum.photos/id/20/200/200',
          type: 'image'
        }
      ],
      
      // 历史记录
      historyStack: [],
      historyPosition: -1,
      maxHistorySteps: 30,

      // 剪贴板对象
      clipboardObject: null,

      // 图层相关
      layers: [],
      activeLayerId: null,
      layerCounter: 0,

      // 添加元素计数器
      elementCounter: 0,
    };
  },
  computed: {
    isTextObject() {
      return this.selectedObject && 
        (this.selectedObject.type === 'i-text' || 
         this.selectedObject.type === 'text' || 
         this.selectedObject.type === 'textbox');
    },
    isImageObject() {
      return this.selectedObject && this.selectedObject.type === 'image';
    },
    isShapeObject() {
      return this.selectedObject && 
        (this.selectedObject.type === 'rect' || 
         this.selectedObject.type === 'circle' || 
         this.selectedObject.type === 'triangle' || 
         this.selectedObject.type === 'polygon' || 
         this.selectedObject.type === 'path');
    }
  },
  watch: {
    // 监听activeTab变化来控制侧边栏显示
    activeTab(newTab) {
      this.showSidebar = ['template', 'text', 'material', 'preview', 'layer'].includes(newTab);
    }
  },
  mounted() {
    // 确保组件完全挂载后再初始化Canvas
    this.$nextTick(() => {
      // 设置默认画布尺寸
      this.workspaceWidth = 800;
      this.workspaceHeight = 600;
      this.workspaceBackground = '#ffffff';
      
      // 初始化画布
        this.initCanvas();
    });
  },
  methods: {
    // 初始化Canvas
    initCanvas() {
      try {
        console.log('开始初始化Canvas...');
        
        // 检查并重置Canvas容器
        const container = document.getElementById('canvas-container');
        if (!container) {
          console.error('找不到Canvas容器!');
          return;
        }
        
        // 确保容器为空并重新创建canvas元素
        container.innerHTML = '<canvas id="fabric-canvas"></canvas>';
        
        // 获取Canvas元素
        const canvasEl = document.getElementById('fabric-canvas');
        if (!canvasEl) {
          console.error('Canvas元素创建失败!');
          return;
        }
        
        // 创建Fabric Canvas实例
        console.log('创建Fabric.js实例...');
        
        // 使用fabric创建新画布，添加更多配置
          this.canvas = new fabric.Canvas('fabric-canvas', {
          width: this.workspaceWidth,
          height: this.workspaceHeight,
          backgroundColor: this.workspaceBackground,
          preserveObjectStacking: true,
          selection: true,
          defaultCursor: 'default',
          hoverCursor: 'pointer',
          stopContextMenu: true, // 禁用右键菜单
          fireRightClick: true, // 启用右键点击事件
          fireMiddleClick: true, // 启用中键点击事件
          perPixelTargetFind: false, // 提高性能
          targetFindTolerance: 4, // 选择容差
          svgViewportTransformation: true, // 支持SVG视图变换
          centeredScaling: true, // 居中缩放
          centeredRotation: true, // 居中旋转
          enableRetinaScaling: true, // 支持视网膜屏幕
          snapAngle: 45, // 旋转吸附角度
          snapThreshold: 10, // 吸附阈值
          selectionColor: 'rgba(24, 144, 255, 0.15)', // 选择区域颜色
          selectionBorderColor: '#1890ff', // 选择边框颜色
          selectionLineWidth: 1, // 选择边框宽度
          selectionDashArray: [4, 4], // 选择边框虚线样式
          controlsAboveOverlay: true, // 控制点在蒙层上方
          cornerStyle: 'circle', // 控制点样式
          cornerSize: 8, // 控制点大小
          cornerColor: '#1890ff', // 控制点颜色
          cornerStrokeColor: '#fff', // 控制点边框颜色
          transparentCorners: false, // 控制点不透明
          rotatingPointOffset: 40, // 旋转控制点偏移
          padding: 0, // 对象内边距
          borderColor: '#1890ff', // 边框颜色
          borderDashArray: null, // 边框实线
          borderOpacityWhenMoving: 0.4, // 移动时边框透明度
          });
          
          // 检查canvas是否创建成功
          if (!this.canvas) {
            console.error('Fabric Canvas创建失败!');
            return;
          }
          
          // 设置基本事件监听
          this.setupBasicEvents();
        
        // 设置键盘事件监听
        this.setupKeyboardEvents();
        
        // 设置画布事件监听
        this.setupCanvasEvents();
          
          // 记录初始历史状态
        this._recordHistory();
          
          // 设置成功状态
          this.initialized = true;
          console.log('Canvas初始化成功!');
          
        // 自动适应画布大小
        this.$nextTick(() => {
          this.fitCanvas();
        });
        
        } catch (err) {
        console.error('Canvas初始化失败:', err);
      }
    },

    // 设置键盘事件监听
    setupKeyboardEvents() {
      document.addEventListener('keydown', (e) => {
        if (!this.canvas) return;

        // 判断是否在输入状态
        const isEditing = this.canvas.getActiveObjects().some(obj => 
          obj.isEditing || (obj.type === 'textbox' && obj.focused)
        );
        if (isEditing) return;

        // 复制 Ctrl+C
        if (e.ctrlKey && e.key === 'c') {
          e.preventDefault();
          this.copySelected();
        }
        // 粘贴 Ctrl+V
        else if (e.ctrlKey && e.key === 'v') {
          e.preventDefault();
          this.pasteObject();
        }
        // 剪切 Ctrl+X
        else if (e.ctrlKey && e.key === 'x') {
          e.preventDefault();
          this.cutSelected();
        }
        // 撤销 Ctrl+Z
        else if (e.ctrlKey && e.key === 'z') {
          e.preventDefault();
          this.undo();
        }
        // 重做 Ctrl+Y
        else if (e.ctrlKey && e.key === 'y') {
          e.preventDefault();
          this.redo();
        }
        // 全选 Ctrl+A
        else if (e.ctrlKey && e.key === 'a') {
          e.preventDefault();
          const objects = this.canvas.getObjects();
          if (objects.length > 0) {
            this.canvas.discardActiveObject();
            const selection = new fabric.ActiveSelection(objects, { canvas: this.canvas });
            this.canvas.setActiveObject(selection);
            this.canvas.requestRenderAll();
          }
        }
        // 删除 Delete
        else if (e.key === 'Delete' || e.key === 'Backspace') {
          if (!isEditing) {
            e.preventDefault();
            this.deleteSelected();
          }
        }
        // 上下左右键移动
        else if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
          e.preventDefault();
          const activeObject = this.canvas.getActiveObject();
          if (!activeObject) return;

          const STEP = e.shiftKey ? 10 : 1; // Shift键按下时移动步长为10
          switch (e.key) {
            case 'ArrowLeft':
              activeObject.left -= STEP;
              break;
            case 'ArrowRight':
              activeObject.left += STEP;
              break;
            case 'ArrowUp':
              activeObject.top -= STEP;
              break;
            case 'ArrowDown':
              activeObject.top += STEP;
              break;
          }
          activeObject.setCoords();
          this.canvas.renderAll();
          this._recordHistory();
        }
      });
    },

    // 设置画布事件监听
    setupCanvasEvents() {
      if (!this.canvas) return;
      
      // 鼠标滚轮缩放
      this.canvas.on('mouse:wheel', (opt) => {
        const delta = opt.e.deltaY;
        let zoom = this.canvas.getZoom();
        zoom *= 0.999 ** delta;
        if (zoom > 20) zoom = 20;
        if (zoom < 0.01) zoom = 0.01;
        
        const point = {
          x: opt.e.offsetX,
          y: opt.e.offsetY
        };
        
        this.canvas.zoomToPoint(point, zoom);
        opt.e.preventDefault();
        opt.e.stopPropagation();
      });

      // 鼠标中键拖动画布
      this.canvas.on('mouse:down', (opt) => {
        if (opt.e.button === 1) { // 中键
          this.canvas.isDragging = true;
          this.canvas.lastPosX = opt.e.clientX;
          this.canvas.lastPosY = opt.e.clientY;
          opt.e.preventDefault();
        }
      });

      this.canvas.on('mouse:move', (opt) => {
        if (this.canvas.isDragging) {
          const e = opt.e;
          const vpt = this.canvas.viewportTransform;
          vpt[4] += e.clientX - this.canvas.lastPosX;
          vpt[5] += e.clientY - this.canvas.lastPosY;
          this.canvas.requestRenderAll();
          this.canvas.lastPosX = e.clientX;
          this.canvas.lastPosY = e.clientY;
          opt.e.preventDefault();
        }
      });

      this.canvas.on('mouse:up', () => {
        this.canvas.isDragging = false;
      });

      // 对象修改后自动保存
      this.canvas.on('object:modified', () => {
        this._recordHistory();
      });

      // 对象选择状态变化
      this.canvas.on('selection:created', (opt) => {
        this.updateControls(opt.target);
      });

      this.canvas.on('selection:updated', (opt) => {
        this.updateControls(opt.target);
      });

      this.canvas.on('selection:cleared', () => {
        this.updateControls(null);
      });
    },

    // 更新控制点
    updateControls(target) {
      if (!target) return;

      const controls = {
        tl: true, // 左上
        tr: true, // 右上
        bl: true, // 左下
        br: true, // 右下
        ml: true, // 中左
        mt: true, // 中上
        mr: true, // 中右
        mb: true, // 中下
        mtr: true // 旋转
      };

      // 根据对象类型设置不同的控制点
      if (target.type === 'line') {
        controls.ml = controls.mr = false;
        controls.mt = controls.mb = false;
      } else if (target.type === 'image') {
        // 保持所有控制点
      } else if (target.type.includes('text')) {
        controls.ml = controls.mr = true;
        controls.mt = controls.mb = false;
      }

      // 应用控制点设置
      Object.keys(controls).forEach(control => {
        target.setControlVisible(control, controls[control]);
      });

      this.canvas.requestRenderAll();
    },
    
    // 添加测试形状
    addTestShape() {
      if (!this.canvas) return;
      
      // 移除测试形状代码
      console.log('Canvas初始化完成');
    },
    
    // 设置基本事件监听
    setupBasicEvents() {
      if (!this.canvas) return;
      
      // 选择事件
      this.canvas.on('selection:created', (e) => {
        console.log('Selection created:', e.target);
        this.selectedObject = e.target;
        this.updateSelectedObjectProps();
        this.updateActiveLayer(e.target);
        this.canvas.renderAll();
      });
      
      this.canvas.on('selection:updated', (e) => {
        console.log('Selection updated:', e.target);
        this.selectedObject = e.target;
        this.updateSelectedObjectProps();
        this.updateActiveLayer(e.target);
        this.canvas.renderAll();
      });
      
      this.canvas.on('selection:cleared', () => {
        console.log('Selection cleared');
        this.selectedObject = null;
        this.selectedObjectProps = {};
        this.activeLayerId = null;
        this.canvas.renderAll();
      });

      // 对象修改事件
      this.canvas.on('object:modified', (e) => {
        console.log('Object modified:', e.target);
        this.selectedObject = e.target;
        this.updateSelectedObjectProps();
        this._recordHistory();
      });

      // 对象选中事件
      this.canvas.on('mouse:down', (e) => {
        if (e.target) {
          console.log('Mouse down on object:', e.target);
          this.selectedObject = e.target;
          this.updateSelectedObjectProps();
          this.updateActiveLayer(e.target);
        }
      });

      // 对象移动事件
      this.canvas.on('object:moving', (e) => {
        this.selectedObject = e.target;
        this.$nextTick(() => {
          this.updateSelectedObjectProps();
        });
      });

      // 对象缩放事件
      this.canvas.on('object:scaling', (e) => {
        this.selectedObject = e.target;
        this.$nextTick(() => {
          this.updateSelectedObjectProps();
        });
      });

      // 对象旋转事件
      this.canvas.on('object:rotating', (e) => {
        this.selectedObject = e.target;
        this.$nextTick(() => {
          this.updateSelectedObjectProps();
        });
      });

      // 对象添加事件
      this.canvas.on('object:added', this.handleObjectAdded);

      // 对象移除事件
      this.canvas.on('object:removed', this.handleObjectRemoved);
      
      console.log('Canvas事件已设置');
    },
    
    // 更新活动图层
    updateActiveLayer(target) {
      if (!target) return;
      
      // 查找对象所在的图层
      const layer = this.layers.find(l => 
        l.objects.some(obj => obj.id === target.id)
      );
      
      if (layer) {
        this.activeLayerId = layer.id;
      }
    },

    // 获取新元素位置
    getNewElementPosition() {
      this.elementCounter++;
      return {
        left: 100 + (this.elementCounter - 1) * 10,
        top: 100 + (this.elementCounter - 1) * 10
      };
    },
    
    // 添加矩形
    addNewRect() {
      if (!this.canvas) return;
      
      const position = this.getNewElementPosition();
      const rect = new fabric.Rect({
        left: position.left,
        top: position.top,
        width: 100,
        height: 100,
        fill: '#3498db',
        stroke: '#2980b9',
        strokeWidth: 1
      });
      
      this.canvas.add(rect);  // 这会触发 object:added 事件
      this.canvas.setActiveObject(rect);
      this.selectedObject = rect;
      this.updateSelectedObjectProps();
      this.canvas.renderAll();
      this._recordHistory();
    },
    
    // 添加圆形
    addNewCircle() {
      if (!this.canvas) return;
      
      const position = this.getNewElementPosition();
      const circle = new fabric.Circle({
        left: position.left,
        top: position.top,
        radius: 50,
        fill: '#e74c3c',
        stroke: '#c0392b',
        strokeWidth: 1
      });
      
      this.canvas.add(circle);  // 这会触发 object:added 事件
      this.canvas.setActiveObject(circle);
      this.selectedObject = circle;
      this.updateSelectedObjectProps();
      this.canvas.renderAll();
      this._recordHistory();
    },
    
    // 添加文本
    addNewText(type = 'paragraph') {
      if (!this.canvas) return;
      
      const position = this.getNewElementPosition();
      let textConfig = {
        left: position.left,
        top: position.top,
        fontFamily: this.defaultFontFamily || 'Arial',
        fill: this.defaultTextColor || '#2c3e50'
      };

      // 根据文本类型设置不同的样式
      switch (type) {
        case 'heading':
          textConfig = {
            ...textConfig,
            text: '大标题',
            fontSize: 32,
            fontWeight: 'bold'
          };
          break;
        case 'subheading':
          textConfig = {
            ...textConfig,
            text: '副标题',
            fontSize: 24,
            fontWeight: '500'
          };
          break;
        case 'paragraph':
          textConfig = {
            ...textConfig,
            text: '正文段落',
            fontSize: 16,
            fontWeight: 'normal'
          };
          break;
        case 'quote':
          textConfig = {
            ...textConfig,
            text: '引用文本',
            fontSize: 16,
            fontStyle: 'italic',
            left: 120,
            backgroundColor: '#f8f9fa',
            padding: 10,
            width: 300,
            textAlign: 'left'
          };
          break;
        case 'caption':
          textConfig = {
            ...textConfig,
            text: '图片说明文本',
            fontSize: 12,
            fill: '#666666',
            textAlign: 'center'
          };
          break;
        default:
          textConfig = {
            ...textConfig,
            text: '双击编辑文本',
            fontSize: 16
          };
      }
      
      const text = new fabric.IText(textConfig.text, textConfig);
      
      this.canvas.add(text);
      this.canvas.setActiveObject(text);
      this.selectedObject = text;
      this.updateSelectedObjectProps();
      this.canvas.renderAll();
      this._recordHistory();
    },
    
    // 添加特殊文字效果
    addSpecialText(effectType) {
      if (!this.canvas) return;
      
      let textConfig = {
        left: 100,
        top: 100,
        text: '特效文字',
        fontSize: 36,
        fontWeight: 'bold',
        fontFamily: this.defaultFontFamily || 'Arial'
      };

      switch (effectType) {
        case 'gradient':
          textConfig = {
            ...textConfig,
            fill: new fabric.Gradient({
              type: 'linear',
              coords: {
                x1: 0,
                y1: 0,
                x2: 1,
                y2: 1
              },
              colorStops: [
                { offset: 0, color: '#1890ff' },
                { offset: 1, color: '#f759ab' }
              ]
            })
          };
          break;
        case 'shadow':
          textConfig = {
            ...textConfig,
            shadow: new fabric.Shadow({
              color: 'rgba(0,0,0,0.3)',
              blur: 4,
              offsetX: 4,
              offsetY: 4
            })
          };
          break;
        case 'outline':
          textConfig = {
            ...textConfig,
            fill: '#ffffff',
            stroke: '#1890ff',
            strokeWidth: 1
          };
          break;
        case 'neon':
          textConfig = {
            ...textConfig,
            fill: '#ffffff',
            stroke: '#1890ff',
            strokeWidth: 1,
            shadow: new fabric.Shadow({
              color: '#1890ff',
              blur: 15,
              offsetX: 0,
              offsetY: 0
            })
          };
          break;
        case 'retro':
          textConfig = {
            ...textConfig,
            fontFamily: 'Courier New',
            fill: '#d35400',
            charSpacing: 100,
            text: textConfig.text.toUpperCase()
          };
          break;
        case 'metallic':
          textConfig = {
            ...textConfig,
            fill: new fabric.Gradient({
              type: 'linear',
              coords: {
                x1: 0,
                y1: 0,
                x2: 0,
                y2: 1
              },
              colorStops: [
                { offset: 0, color: '#ffffff' },
                { offset: 0.5, color: '#c0c0c0' },
                { offset: 1, color: '#ffffff' }
              ]
            }),
            shadow: new fabric.Shadow({
              color: 'rgba(0,0,0,0.2)',
              blur: 3,
              offsetX: 2,
              offsetY: 2
            })
          };
          break;
      }

      const text = new fabric.IText(textConfig.text, textConfig);
      this.canvas.add(text);
      this.canvas.setActiveObject(text);
      this.canvas.renderAll();
    },
    
    // 创建空白画布
    createBlankCanvas(size) {
      console.log('Creating blank canvas with size:', size);
      
      // 如果canvas不存在，先初始化canvas
      if (!this.canvas) {
        this.workspaceWidth = size.width;
        this.workspaceHeight = size.height;
        this.initCanvas();
        return;
      }
      
      // 清空当前画布
      this.clearCanvas();
      
      // 设置画布尺寸
      this.workspaceWidth = size.width;
      this.workspaceHeight = size.height;
      
      // 更新画布尺寸
      this.canvas.setWidth(size.width);
      this.canvas.setHeight(size.height);
      
      // 设置背景色
      this.canvas.backgroundColor = this.workspaceBackground;
      this.backgroundColor = this.workspaceBackground;
      
      // 重置缩放
      this.zoomLevel = 1;
      this.canvas.setZoom(1);
      
      // 重置画布中心点
      this.canvas.viewportTransform[4] = 0;
      this.canvas.viewportTransform[5] = 0;
      
      // 重新渲染
      this.canvas.renderAll();
      
      // 记录历史
      this._recordHistory();
      
      // 自动适应画布大小
      this.$nextTick(() => {
        this.fitCanvas();
      });
      
      console.log('创建空白画布成功:', size);
    },
    
    // 创建自定义尺寸画布
    createCustomCanvas({ width, height }) {
      console.log('Creating custom canvas:', width, height);
      
      if (!width || !height) {
        console.error('无效的画布尺寸');
        return;
      }
      
      // 限制最大和最小尺寸
      width = Math.min(Math.max(width, 100), 3000);
      height = Math.min(Math.max(height, 100), 3000);
      
      this.createBlankCanvas({
        width: parseInt(width),
        height: parseInt(height)
      });
    },
    
    // 清空画布
    clearCanvas() {
      if (!this.canvas) return;
      
      // 标记所有对象为跳过图层添加
      this.canvas.getObjects().forEach(obj => {
        obj.skipLayerAdd = true;
      });
      
      // 清除所有对象
      this.canvas.clear();
      
      // 重置背景色
      this.canvas.backgroundColor = '#ffffff';
      this.backgroundColor = '#ffffff';
      
      // 清除选中状态
      this.selectedObject = null;
      this.selectedObjectProps = {};
      
      // 清除所有图层
      this.layers = [];
      this.activeLayerId = null;
      this.layerCounter = 0;
      
      // 重置元素计数器
      this.elementCounter = 0;
      
      // 重置画布变换
      this.canvas.viewportTransform = [1, 0, 0, 1, 0, 0];
      
      // 重新渲染
      this.canvas.renderAll();
      
      // 记录历史
      this._recordHistory();
    },
    
    // 获取随机颜色
    getRandomColor() {
      return '#' + Math.floor(Math.random() * 16777215).toString(16);
    },
    
    // 标签导航
    switchTab(tab) {
      this.activeTab = tab;
      if (tab === 'layer') {
        // 确保在切换到图层标签时显示图层面板
        this.showSidebar = true;
      }
    },
    
    // 侧边栏控制
    toggleLeftSidebar() {
      this.leftSidebarCollapsed = !this.leftSidebarCollapsed;
      // 重新渲染以适应新宽度
      setTimeout(() => {
        this.canvas && this.canvas.renderAll();
      }, 300);
    },
    
    toggleRightSidebar() {
      this.rightSidebarCollapsed = !this.rightSidebarCollapsed;
      // 重新渲染以适应新宽度
      setTimeout(() => {
        this.canvas && this.canvas.renderAll();
      }, 300);
    },

    // 更新选中对象属性
    updateSelectedObjectProps() {
      if (!this.selectedObject) {
        console.log('No selected object');
        this.selectedObjectProps = {};
        return;
      }
      
      console.log('Updating properties for:', this.selectedObject);
      
      try {
      // 基本属性
        const props = {
          left: Math.round(this.selectedObject.left || 0),
          top: Math.round(this.selectedObject.top || 0),
          width: Math.round(this.selectedObject.getScaledWidth() || 0),
          height: Math.round(this.selectedObject.getScaledHeight() || 0),
          angle: Math.round(this.selectedObject.angle || 0),
          opacity: this.selectedObject.opacity || 1,
        fill: this.selectedObject.fill || '#000000',
        stroke: this.selectedObject.stroke || '#000000',
        strokeWidth: this.selectedObject.strokeWidth || 0
      };
      
      // 文本特有属性
      if (this.isTextObject) {
          console.log('Updating text properties');
          Object.assign(props, {
            text: this.selectedObject.text || '',
            fontFamily: this.selectedObject.fontFamily || 'Arial',
            fontSize: this.selectedObject.fontSize || 16,
            fontWeight: this.selectedObject.fontWeight || 'normal',
            fontStyle: this.selectedObject.fontStyle || 'normal',
            underline: this.selectedObject.underline || false,
            textAlign: this.selectedObject.textAlign || 'left',
            charSpacing: this.selectedObject.charSpacing || 0
          });
        }

        // 立即更新属性
        this.$nextTick(() => {
          this.selectedObjectProps = { ...props };
          console.log('Updated properties:', this.selectedObjectProps);
        });
      } catch (error) {
        console.error('Error updating properties:', error);
      }
    },
    
    // 更新对象属性
    updateObjectProperty(property) {
      if (!this.selectedObject) return;
      
      const value = this.selectedObjectProps[property];
      
      // 处理特殊属性
      switch (property) {
        case 'width':
          this.selectedObject.scaleToWidth(value);
          break;
        case 'height':
          this.selectedObject.scaleToHeight(value);
          break;
        case 'fill':
        case 'stroke':
          this.selectedObject.set(property, value || (property === 'fill' ? '#000000' : 'rgba(0,0,0,0)'));
          break;
        default:
          this.selectedObject.set(property, value);
      }
      
      this.selectedObject.setCoords();
      this.canvas.renderAll();
      
      // 记录历史
      this._recordHistory();
      
      // 更新属性面板
      this.updateSelectedObjectProps();
    },
    
    // 文本样式
    toggleBold() {
      if (!this.canvas || !this.isTextObject) return;
      
      const activeObject = this.canvas.getActiveObject();
      activeObject.set('fontWeight', activeObject.fontWeight === 'bold' ? 'normal' : 'bold');
      this.canvas.renderAll();
      this.updateSelectedObjectProps();
    },
    
    toggleItalic() {
      if (!this.canvas || !this.isTextObject) return;
      
      const activeObject = this.canvas.getActiveObject();
      activeObject.set('fontStyle', activeObject.fontStyle === 'italic' ? 'normal' : 'italic');
      this.canvas.renderAll();
      this.updateSelectedObjectProps();
    },
    
    toggleUnderline() {
      if (!this.canvas || !this.isTextObject) return;
      
      const activeObject = this.canvas.getActiveObject();
      activeObject.set('underline', !activeObject.underline);
      this.canvas.renderAll();
      this.updateSelectedObjectProps();
    },
    
    // 颜色设置
    setColor(color) {
      if (!this.canvas) return;
      
      // 确保颜色值有效
      color = color || '#000000';
      
      const activeObject = this.canvas.getActiveObject();
      if (!activeObject) {
        this.defaultTextColor = color;
        return;
      }

      activeObject.set('fill', color);
      this.canvas.renderAll();
      this.updateSelectedObjectProps();
    },
    
    // 背景设置
    setBackgroundColor(color) {
      if (!this.canvas) return;
      
      this.backgroundColor = color;
      this.canvas.backgroundColor = color;
      this.canvas.renderAll();
    },
    
    // 编辑操作
    copySelected() {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (activeObject) {
        // 保存当前选中的对象
        activeObject.clone((cloned) => {
          this.clipboardObject = cloned;
        });
      }
    },
    
    cutSelected() {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (activeObject) {
        // 保存当前选中的对象
        activeObject.clone((cloned) => {
          this.clipboardObject = cloned;
          this.deleteSelected();
        });
      }
    },
    
    pasteObject() {
      if (!this.canvas || !this.clipboardObject) return;
      
      this.clipboardObject.clone((clonedObj) => {
        // 调整新对象的位置，避免完全重叠
        clonedObj.set({
          left: clonedObj.left + 20,
          top: clonedObj.top + 20,
          evented: true,
        });
        
        this.canvas.add(clonedObj);
        this.canvas.setActiveObject(clonedObj);
        this.canvas.renderAll();
        this._recordHistory();
      });
    },
    
    deleteSelected() {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (activeObject) {
        if (activeObject.type === 'activeSelection') {
          activeObject.forEachObject(obj => this.canvas.remove(obj));
          this.canvas.discardActiveObject();
        } else {
          this.canvas.remove(activeObject);
        }
        
        this.canvas.renderAll();
        this._recordHistory();
      }
    },
    
    // 缩放控制
    zoomIn() {
      if (!this.canvas) return;
      
      const currentZoom = this.canvas.getZoom();
      this.zoomLevel = currentZoom * 1.1;
      this.canvas.setZoom(this.zoomLevel);
      this.canvas.renderAll();
    },
    
    zoomOut() {
      if (!this.canvas) return;
      
      const currentZoom = this.canvas.getZoom();
      this.zoomLevel = currentZoom * 0.9;
      this.canvas.setZoom(this.zoomLevel);
      this.canvas.renderAll();
    },
    
    fitCanvas() {
      if (!this.canvas) return;
      
      // 获取容器尺寸
      const container = document.querySelector('.canvas-wrapper');
      if (!container) return;
      
      const containerWidth = container.clientWidth - 40; // 减去内边距
      const containerHeight = container.clientHeight - 40;
      
      // 计算缩放比例
      const scaleX = containerWidth / this.workspaceWidth;
      const scaleY = containerHeight / this.workspaceHeight;
      const scale = Math.min(scaleX, scaleY, 1); // 限制最大缩放为1
      
      // 设置缩放
      this.zoomLevel = scale;
      this.canvas.setZoom(scale);
      
      // 计算居中位置
      const left = (containerWidth - this.workspaceWidth * scale) / 2;
      const top = (containerHeight - this.workspaceHeight * scale) / 2;
      
      // 设置画布位置
      this.canvas.viewportTransform[4] = left;
      this.canvas.viewportTransform[5] = top;
      
      // 重新渲染
      this.canvas.renderAll();
      
      console.log('Canvas自适应完成:', {
        containerSize: { width: containerWidth, height: containerHeight },
        canvasSize: { width: this.workspaceWidth, height: this.workspaceHeight },
        scale,
        position: { left, top }
      });
    },
    
    originalSize() {
      if (!this.canvas) return;
      
      // 恢复原始尺寸
      this.zoomLevel = 1;
      this.canvas.setZoom(1);
      this.canvas.renderAll();
    },
    
    // 记录历史
    _recordHistory() {
      if (!this.canvas) return;
      
      // 如果不在栈顶，移除未来状态
      if (this.historyPosition < this.historyStack.length - 1) {
        this.historyStack = this.historyStack.slice(0, this.historyPosition + 1);
      }
      
      // 保存当前状态
      const json = this.canvas.toJSON(['id', 'name']);
      this.historyStack.push(json);
      
      // 限制历史大小
      if (this.historyStack.length > this.maxHistorySteps) {
        this.historyStack.shift();
      } else {
        this.historyPosition++;
      }
    },
    
    // 撤销/重做
    undo() {
      if (!this.canvas || this.historyPosition <= 0) return;
      
      this.historyPosition--;
      this._restoreHistory();
    },
    
    redo() {
      if (!this.canvas || this.historyPosition >= this.historyStack.length - 1) return;
      
      this.historyPosition++;
      this._restoreHistory();
    },
    
    _restoreHistory() {
      if (!this.canvas) return;
      
      this.canvas.loadFromJSON(this.historyStack[this.historyPosition], () => {
        this.canvas.renderAll();
      });
    },
    
    // 预览与导出
    getPreviewDimensions() {
      switch (this.previewDevice) {
        case 'desktop':
          return '1920 × 1080';
        case 'tablet':
          return '768 × 1024';
        case 'mobile':
          return '375 × 667';
        default:
          return `${this.workspaceWidth} × ${this.workspaceHeight}`;
      }
    },
    
    previewDesign() {
      if (!this.canvas) return;
      
      // 创建预览窗口
      const previewWindow = window.open('', '_blank');
      previewWindow.document.write(`
        <html>
          <head>
            <title>预览设计</title>
            <style>
              body {
                margin: 0;
                padding: 20px;
                display: flex;
                flex-direction: column;
                align-items: center;
                background: #f5f5f5;
                min-height: 100vh;
              }
              .preview-container {
                background: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
              }
              .preview-image {
                max-width: 100%;
                height: auto;
                display: block;
              }
              .preview-controls {
                margin-top: 20px;
                display: flex;
                gap: 10px;
                justify-content: center;
              }
              .preview-button {
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                background: #1890ff;
                color: white;
                cursor: pointer;
                transition: all 0.2s;
              }
              .preview-button:hover {
                background: #40a9ff;
              }
            </style>
          </head>
          <body>
            <div class="preview-container">
              <img src="${this.canvas.toDataURL()}" class="preview-image" />
              <div class="preview-controls">
                <button class="preview-button" onclick="window.print()">打印</button>
                <button class="preview-button" onclick="window.close()">关闭</button>
              </div>
            </div>
          </body>
        </html>
      `);
      previewWindow.document.close();
    },
    
    handleDimensionChange(dimension, value) {
      value = parseInt(value);
      
      if (dimension === 'width') {
        this.exportWidth = value;
        if (this.maintainAspectRatio) {
          const ratio = this.workspaceHeight / this.workspaceWidth;
          this.exportHeight = Math.round(value * ratio);
        }
      } else if (dimension === 'height') {
        this.exportHeight = value;
        if (this.maintainAspectRatio) {
          const ratio = this.workspaceWidth / this.workspaceHeight;
          this.exportWidth = Math.round(value * ratio);
        }
      }
    },
    
    saveDesign() {
      if (!this.canvas) return;
      
      try {
        // 导出为JSON
        const designJson = this.canvas.toJSON(['id', 'name']);
        const designData = JSON.stringify(designJson);
        
        // 保存到本地存储
        localStorage.setItem('savedDesign', designData);
        alert('设计已保存到本地存储');
      } catch (error) {
        console.error('保存设计失败:', error);
      }
    },
    
    async exportDesign() {
      try {
        if (!this.canvas) return;
        
        // 保存当前状态
        const originalWidth = this.canvas.getWidth();
        const originalHeight = this.canvas.getHeight();
        const originalZoom = this.canvas.getZoom();
        
        // 设置导出尺寸
        this.canvas.setWidth(this.exportWidth);
        this.canvas.setHeight(this.exportHeight);
        
        // 调整缩放以适应新尺寸
        const scaleX = this.exportWidth / originalWidth;
        const scaleY = this.exportHeight / originalHeight;
        const scale = Math.min(scaleX, scaleY);
        this.canvas.setZoom(scale);
        
        // 导出为数据URL
        const format = this.exportFormat.toLowerCase();
        const quality = this.exportQuality / 100;
        const dataUrl = this.canvas.toDataURL({
          format: format === 'jpg' ? 'jpeg' : format,
          quality: quality,
          multiplier: 1,
          enableRetinaScaling: true
        });
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = dataUrl;
        link.download = `design-${Date.now()}.${this.exportFormat}`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 恢复原始状态
        this.canvas.setWidth(originalWidth);
        this.canvas.setHeight(originalHeight);
        this.canvas.setZoom(originalZoom);
        this.canvas.renderAll();
      } catch (error) {
        console.error('导出设计失败:', error);
      }
    },
    
    // 模板相关方法
    async applyDesignTemplate(template) {
      if (!this.canvas || !template) return;
      
      try {
        // 清空当前画布
        this.clearCanvas();
        
        // 设置画布尺寸
        this.workspaceWidth = template.width;
        this.workspaceHeight = template.height;
        this.canvas.setWidth(template.width);
        this.canvas.setHeight(template.height);
        
        // 设置背景
        if (template.background) {
          if (template.background.type === 'color') {
            this.canvas.backgroundColor = template.background.value;
            this.backgroundColor = template.background.value;
          } else if (template.background.type === 'gradient') {
            const gradient = new fabric.Gradient(template.background.value);
            this.canvas.setBackgroundColor(gradient);
          } else if (template.background.type === 'image') {
            await this.setBackgroundImage(template.background.value);
          }
        }
        
        // 添加元素
        for (const element of template.elements) {
          await this.addTemplateElement(element);
        }
        
        // 渲染画布
        this.canvas.renderAll();
        
        // 记录历史
        this._recordHistory();
        
        // 重置缩放以适应画布
        this.fitCanvas();
        
        console.log('模板应用成功:', template.name);
      } catch (error) {
        console.error('应用模板失败:', error);
      }
    },
    
    async addTemplateElement(element) {
      if (!element || !element.type) return;
      
      try {
        let obj;
        
        switch (element.type) {
          case 'text':
          case 'i-text':
            obj = new fabric.IText(element.text, {
              ...element,
              selectable: true,
              hasControls: true,
              fontFamily: element.fontFamily || this.defaultFontFamily,
              fill: element.fill || this.defaultTextColor
            });
            break;
            
          case 'image':
            obj = await new Promise((resolve, reject) => {
              fabric.Image.fromURL(element.src, 
                (img) => {
                  img.set({
                    ...element,
                    selectable: true,
                    hasControls: true,
                    crossOrigin: 'anonymous'
                  });
                  resolve(img);
                },
                { crossOrigin: 'anonymous' }
              );
            });
            break;
            
          case 'rect':
            obj = new fabric.Rect({
              ...element,
              selectable: true,
              hasControls: true,
              fill: element.fill || this.defaultShapeFill,
              stroke: element.stroke || this.defaultShapeStroke
            });
            break;
            
          case 'circle':
            obj = new fabric.Circle({
              ...element,
              selectable: true,
              hasControls: true,
              fill: element.fill || this.defaultShapeFill,
              stroke: element.stroke || this.defaultShapeStroke
            });
            break;
            
          case 'line':
            obj = new fabric.Line(element.points || [0, 0, 100, 100], {
              ...element,
              selectable: true,
              hasControls: true,
              stroke: element.stroke || this.defaultShapeStroke
            });
            break;
            
          case 'path':
            obj = new fabric.Path(element.path, {
              ...element,
              selectable: true,
              hasControls: true,
              fill: element.fill || this.defaultShapeFill,
              stroke: element.stroke || this.defaultShapeStroke
            });
            break;
        }
        
        if (obj) {
          // 设置通用属性
          if (element.opacity !== undefined) {
            obj.set('opacity', element.opacity);
          }
          
          // 设置阴影
          if (element.shadow) {
            obj.setShadow(new fabric.Shadow(element.shadow));
          }
          
          // 设置变换属性
          if (element.angle) {
            obj.rotate(element.angle);
          }
          
          if (element.scaleX || element.scaleY) {
            obj.scale(element.scaleX || 1, element.scaleY || 1);
          }
          
          if (element.flipX || element.flipY) {
            obj.set({
              flipX: element.flipX || false,
              flipY: element.flipY || false
            });
          }
          
          // 添加到画布
          this.canvas.add(obj);
          
          // 确保对象在正确的位置
          obj.setCoords();
        }
      } catch (error) {
        console.error('添加模板元素失败:', error);
      }
    },
    
    async setBackgroundImage(imageUrl) {
      return new Promise((resolve, reject) => {
        fabric.Image.fromURL(
          imageUrl,
          (img) => {
            // 调整图片大小以适应画布
            const scaleX = this.canvas.width / img.width;
            const scaleY = this.canvas.height / img.height;
            const scale = Math.max(scaleX, scaleY);
            
            img.scale(scale);
            
            this.canvas.setBackgroundImage(
              img,
              this.canvas.renderAll.bind(this.canvas),
              {
                originX: 'left',
                originY: 'top',
                left: 0,
                top: 0
              }
            );
            resolve();
          },
          { crossOrigin: 'anonymous' }
        );
      });
    },
    
    // 保存为模板
    async saveAsTemplate() {
      if (!this.canvas) return;
      
      try {
        // 获取当前画布的JSON数据
        const canvasData = this.canvas.toJSON(['id', 'name', 'selectable', 'hasControls']);
        
        // 创建新模板对象
        const newTemplate = {
          id: `template_${Date.now()}`,
          name: '自定义模板',
          category: 'custom',
          thumbnail: this.canvas.toDataURL({
            format: 'jpeg',
            quality: 0.8,
            multiplier: 0.5
          }),
          width: this.canvas.width,
          height: this.canvas.height,
          description: '用户自定义模板',
          elements: canvasData.objects.map(obj => ({
            ...obj,
            selectable: true,
            hasControls: true
          })),
          background: {
            type: this.backgroundType,
            value: this.backgroundType === 'color' ? this.backgroundColor : canvasData.background
          }
        };
        
        // 添加到模板列表
        this.designTemplates.unshift(newTemplate);
        
        console.log('模板保存成功:', newTemplate);
        return newTemplate;
      } catch (error) {
        console.error('保存模板失败:', error);
      }
    },
    
    // 删除模板
    deleteTemplate(templateId) {
      const index = this.designTemplates.findIndex(t => t.id === templateId);
      if (index !== -1) {
        this.designTemplates.splice(index, 1);
        console.log('模板删除成功:', templateId);
      }
    },
    
    // 更新模板
    updateTemplate(templateId, updates) {
      const template = this.designTemplates.find(t => t.id === templateId);
      if (template) {
        Object.assign(template, updates);
        console.log('模板更新成功:', template);
      }
    },
    
    // 复制模板
    duplicateTemplate(templateId) {
      const template = this.designTemplates.find(t => t.id === templateId);
      if (template) {
        const newTemplate = {
          ...template,
          id: `template_${Date.now()}`,
          name: `${template.name} 副本`,
          description: `${template.description} (副本)`
        };
        this.designTemplates.unshift(newTemplate);
        console.log('模板复制成功:', newTemplate);
        return newTemplate;
      }
    },
    
    // 模板相关方法
    applyTemplate(template) {
      console.log('应用模板:', template);
      // 实现模板应用逻辑
    },
    
    // 素材相关方法
    addMaterial(material) {
      if (!this.canvas) return;
      
      fabric.Image.fromURL(material.url, (img) => {
        // 缩放图片，确保不超过画布
        const maxWidth = this.canvas.width * 0.7;
        const maxHeight = this.canvas.height * 0.7;
        
        if (img.width > maxWidth || img.height > maxHeight) {
          const scale = Math.min(maxWidth / img.width, maxHeight / img.height);
          img.scale(scale);
        }
        
        img.set({
          left: this.canvas.width / 2 - img.width * img.scaleX / 2,
          top: this.canvas.height / 2 - img.height * img.scaleY / 2,
          name: material.name
        });
        
        this.canvas.add(img);  // 这会触发 object:added 事件
        this.canvas.setActiveObject(img);
        this.selectedObject = img;
        this.updateSelectedObjectProps();
        this.canvas.renderAll();
        this._recordHistory();
      }, { crossOrigin: 'anonymous' });
    },
    
    async handleImageUpload(event) {
      if (!this.canvas || !event.target.files.length) return;
      
      const file = event.target.files[0];
      try {
        const dataUrl = await fileToDataURL(file);
        fabric.Image.fromURL(dataUrl, (img) => {
          // 缩放图片，确保不超过画布
          const maxWidth = this.canvas.width * 0.7;
          const maxHeight = this.canvas.height * 0.7;
          
          if (img.width > maxWidth || img.height > maxHeight) {
            const scale = Math.min(maxWidth / img.width, maxHeight / img.height);
            img.scale(scale);
          }
          
          img.set({
            left: this.canvas.width / 2 - img.width * img.scaleX / 2,
            top: this.canvas.height / 2 - img.height * img.scaleY / 2,
            name: file.name
          });
          
          this.canvas.add(img);
          this.canvas.setActiveObject(img);
          this.selectedObject = img;
          this.updateSelectedObjectProps();
          this.canvas.renderAll();
          this._recordHistory();
        });
      } catch (error) {
        console.error('上传图片失败:', error);
      }
    },
    
    // 添加三角形
    addTriangle() {
      if (!this.canvas) return;
      
      const position = this.getNewElementPosition();
      const triangle = new fabric.Triangle({
        left: position.left,
        top: position.top,
        width: 100,
        height: 100,
        fill: this.defaultShapeFill,
        stroke: this.defaultShapeStroke,
        strokeWidth: 1
      });
      
      this.canvas.add(triangle);  // 这会触发 object:added 事件
      this.canvas.setActiveObject(triangle);
      this.selectedObject = triangle;
      this.updateSelectedObjectProps();
      this.canvas.renderAll();
      this._recordHistory();
    },
    
    // 添加多边形
    addPolygon() {
      if (!this.canvas) return;
      
      const position = this.getNewElementPosition();
      const points = [
        { x: 0, y: 0 },
        { x: 50, y: 0 },
        { x: 75, y: 50 },
        { x: 50, y: 100 },
        { x: 0, y: 100 },
        { x: -25, y: 50 }
      ];
      
      const polygon = new fabric.Polygon(points, {
        left: position.left,
        top: position.top,
        fill: this.defaultShapeFill,
        stroke: this.defaultShapeStroke,
        strokeWidth: 1
      });
      
      this.canvas.add(polygon);  // 这会触发 object:added 事件
      this.canvas.setActiveObject(polygon);
      this.selectedObject = polygon;
      this.updateSelectedObjectProps();
      this.canvas.renderAll();
      this._recordHistory();
    },
    
    // 添加线条
    drawLine() {
      if (!this.canvas) return;
      
      const position = this.getNewElementPosition();
      const line = new fabric.Line([0, 0, 150, 150], {
        left: position.left,
        top: position.top,
        stroke: this.defaultShapeStroke,
        strokeWidth: 2
      });
      
      this.canvas.add(line);  // 这会触发 object:added 事件
      this.canvas.setActiveObject(line);
      this.selectedObject = line;
      this.updateSelectedObjectProps();
      this.canvas.renderAll();
      this._recordHistory();
    },

    // 图层相关方法
    addLayer(name = null) {
      const layerId = `layer_${++this.layerCounter}`;
      const newLayer = {
        id: layerId,
        name: name || `图层 ${this.layerCounter}`,
        visible: true,
        locked: false,
        objects: []
      };
      this.layers.unshift(newLayer);  // 添加到数组开头
      this.activeLayerId = layerId;
      return layerId;
    },
    
    deleteLayer() {
      if (!this.activeLayerId) return;
      
      const layerIndex = this.layers.findIndex(l => l.id === this.activeLayerId);
      if (layerIndex === -1) return;
      
      const layer = this.layers[layerIndex];
      // 删除图层中的所有对象
      layer.objects.forEach(obj => {
        this.canvas.remove(obj);
      });
      
      // 删除图层
      this.layers.splice(layerIndex, 1);
      this.activeLayerId = this.layers.length > 0 ? this.layers[0].id : null;
    },
    
    selectLayer(layerId) {
      const layer = this.layers.find(l => l.id === layerId);
      if (!layer || layer.objects.length === 0) return;

      // 设置活动图层
      this.activeLayerId = layerId;

      // 选中图层中的对象
      const obj = layer.objects[0]; // 每个图层只有一个对象
      if (obj) {
        this.canvas.setActiveObject(obj);
        this.selectedObject = obj;
        this.updateSelectedObjectProps();
        this.canvas.renderAll();
      }
    },
    
    toggleLayerVisibility(layerId) {
      const layer = this.layers.find(l => l.id === layerId);
      if (layer) {
        layer.visible = !layer.visible;
        layer.objects.forEach(obj => {
          obj.visible = layer.visible;
        });
        this.canvas.renderAll();
      }
    },
    
    toggleLayerLock(layerId) {
      const layer = this.layers.find(l => l.id === layerId);
      if (layer) {
        layer.locked = !layer.locked;
        layer.objects.forEach(obj => {
          obj.selectable = !layer.locked;
          obj.evented = !layer.locked;
        });
        this.canvas.renderAll();
      }
    },

    // 处理对象添加事件
    handleObjectAdded(e) {
      const obj = e.target;
      if (!obj || obj.skipLayerAdd) return;

      // 为新对象创建图层名称
      let layerName;
      switch (obj.type) {
        case 'rect':
          layerName = `矩形 ${this.layerCounter + 1}`;
          break;
        case 'circle':
          layerName = `圆形 ${this.layerCounter + 1}`;
          break;
        case 'triangle':
          layerName = `三角形 ${this.layerCounter + 1}`;
          break;
        case 'polygon':
          layerName = `多边形 ${this.layerCounter + 1}`;
          break;
        case 'line':
          layerName = `线条 ${this.layerCounter + 1}`;
          break;
        case 'i-text':
        case 'text':
        case 'textbox':
          layerName = `文本 ${this.layerCounter + 1}`;
          break;
        case 'image':
          layerName = `图片 ${this.layerCounter + 1}`;
          break;
        default:
          layerName = `元素 ${this.layerCounter + 1}`;
      }

      // 创建新图层
      const layerId = this.addLayer(layerName);
      const layer = this.layers.find(l => l.id === layerId);

      if (layer) {
        // 确保对象有唯一ID
        obj.id = `obj_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        obj.name = layerName;

        // 将对象添加到图层
        layer.objects = [obj];

        // 应用图层的可见性和锁定状态
        obj.visible = layer.visible;
        obj.selectable = !layer.locked;
        obj.evented = !layer.locked;

        // 强制更新图层数组
        this.layers = [...this.layers];
      }
    },

    // 处理对象移除
    handleObjectRemoved(e) {
      const obj = e.target;
      if (!obj) return;
      
      // 从所有图层中移除该对象
      this.layers = this.layers.filter(layer => {
        const hasObject = layer.objects.some(o => o.id === obj.id);
        return !hasObject;
      });

      // 如果移除的是当前选中对象，清除选中状态
      if (this.selectedObject && this.selectedObject.id === obj.id) {
        this.selectedObject = null;
        this.selectedObjectProps = {};
        this.activeLayerId = null;
      }
    },

    // 对象对齐
    alignObjects(direction) {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (!activeObject) return;
      
      let value;
      switch (direction) {
        case 'left':
          value = 0;
          break;
        case 'center':
          value = this.canvas.width / 2;
          break;
        case 'right':
          value = this.canvas.width;
          break;
        case 'top':
          value = 0;
          break;
        case 'middle':
          value = this.canvas.height / 2;
          break;
        case 'bottom':
          value = this.canvas.height;
          break;
      }
      
      if (['left', 'center', 'right'].includes(direction)) {
        if (activeObject.type === 'activeSelection') {
          const group = activeObject;
          group.forEachObject((obj) => {
            const objWidth = obj.getScaledWidth();
            switch (direction) {
              case 'left':
                obj.set('left', value);
                break;
              case 'center':
                obj.set('left', value - objWidth / 2);
                break;
              case 'right':
                obj.set('left', value - objWidth);
                break;
            }
          });
        } else {
          const objWidth = activeObject.getScaledWidth();
          switch (direction) {
            case 'left':
              activeObject.set('left', value);
              break;
            case 'center':
              activeObject.set('left', value - objWidth / 2);
              break;
            case 'right':
              activeObject.set('left', value - objWidth);
              break;
          }
        }
      } else {
        if (activeObject.type === 'activeSelection') {
          const group = activeObject;
          group.forEachObject((obj) => {
            const objHeight = obj.getScaledHeight();
            switch (direction) {
              case 'top':
                obj.set('top', value);
                break;
              case 'middle':
                obj.set('top', value - objHeight / 2);
                break;
              case 'bottom':
                obj.set('top', value - objHeight);
                break;
            }
          });
        } else {
          const objHeight = activeObject.getScaledHeight();
          switch (direction) {
            case 'top':
              activeObject.set('top', value);
              break;
            case 'middle':
              activeObject.set('top', value - objHeight / 2);
              break;
            case 'bottom':
              activeObject.set('top', value - objHeight);
              break;
          }
        }
      }
      
      activeObject.setCoords();
      this.canvas.renderAll();
      this._recordHistory();
    },

    // 分布对象
    distributeObjects(direction) {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (!activeObject || activeObject.type !== 'activeSelection') return;
      
      const group = activeObject;
      const objects = group.getObjects();
      if (objects.length < 3) return; // 至少需要3个对象才能分布
      
      // 按位置排序
      objects.sort((a, b) => {
        return direction === 'horizontal' ? a.left - b.left : a.top - b.top;
      });
      
      const first = objects[0];
      const last = objects[objects.length - 1];
      const totalSpace = direction === 'horizontal' ?
        last.left - first.left :
        last.top - first.top;
      
      const spacing = totalSpace / (objects.length - 1);
      
      objects.forEach((obj, i) => {
        if (i === 0 || i === objects.length - 1) return; // 跳过首尾对象
        
        if (direction === 'horizontal') {
          obj.set('left', first.left + spacing * i);
        } else {
          obj.set('top', first.top + spacing * i);
        }
      });
      
      group.setCoords();
      this.canvas.renderAll();
      this._recordHistory();
    },

    // 图层排序
    arrangeLayer(direction) {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (!activeObject) return;
      
      switch (direction) {
        case 'front':
          activeObject.bringToFront();
          break;
        case 'forward':
          activeObject.bringForward();
          break;
        case 'backward':
          activeObject.sendBackwards();
          break;
        case 'back':
          activeObject.sendToBack();
          break;
      }
      
      this.canvas.renderAll();
      this._recordHistory();
    },

    // 锁定/解锁对象
    toggleLock() {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (!activeObject) return;
      
      const isLocked = activeObject.lockMovementX && activeObject.lockMovementY;
      
      if (activeObject.type === 'activeSelection') {
        activeObject.forEachObject((obj) => {
          this._setObjectLock(obj, !isLocked);
        });
      } else {
        this._setObjectLock(activeObject, !isLocked);
      }
      
      this.canvas.renderAll();
      this._recordHistory();
    },

    // 设置对象锁定状态
    _setObjectLock(object, locked) {
      object.set({
        lockMovementX: locked,
        lockMovementY: locked,
        lockRotation: locked,
        lockScalingX: locked,
        lockScalingY: locked,
        hasControls: !locked,
        selectable: !locked
      });
    },

    // 组合/解组对象
    toggleGroup() {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (!activeObject) return;
      
      if (activeObject.type === 'activeSelection') {
        // 组合
        activeObject.toGroup();
      } else if (activeObject.type === 'group') {
        // 解组
        activeObject.toActiveSelection();
      }
      
      this.canvas.renderAll();
      this._recordHistory();
    },

    // 翻转对象
    flipObject(direction) {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (!activeObject) return;
      
      if (direction === 'horizontal') {
        activeObject.set('flipX', !activeObject.flipX);
      } else {
        activeObject.set('flipY', !activeObject.flipY);
      }
      
      this.canvas.renderAll();
      this._recordHistory();
    },

    // 克隆对象
    cloneObject() {
      if (!this.canvas) return;
      
      const activeObject = this.canvas.getActiveObject();
      if (!activeObject) return;
      
      activeObject.clone((cloned) => {
        cloned.set({
          left: activeObject.left + 20,
          top: activeObject.top + 20
        });
        
        if (cloned.type === 'activeSelection') {
          // 处理多选克隆
          cloned.canvas = this.canvas;
          cloned.forEachObject((obj) => {
            this.canvas.add(obj);
          });
          this.canvas.setActiveObject(cloned);
        } else {
          this.canvas.add(cloned);
          this.canvas.setActiveObject(cloned);
        }
        
        this.canvas.renderAll();
        this._recordHistory();
      });
    },

    // 显示/隐藏网格
    toggleGrid() {
      if (!this.canvas) return;
      
      this.showGrid = !this.showGrid;
      
      if (this.showGrid) {
        // 创建网格
        const gridSize = 20;
        const gridLines = [];
        
        // 垂直线
        for (let i = 0; i < (this.canvas.width / gridSize); i++) {
          gridLines.push(new fabric.Line([i * gridSize, 0, i * gridSize, this.canvas.height], {
            stroke: '#ccc',
            strokeWidth: 0.5,
            selectable: false,
            evented: false
          }));
        }
        
        // 水平线
        for (let i = 0; i < (this.canvas.height / gridSize); i++) {
          gridLines.push(new fabric.Line([0, i * gridSize, this.canvas.width, i * gridSize], {
            stroke: '#ccc',
            strokeWidth: 0.5,
            selectable: false,
            evented: false
          }));
        }
        
        // 添加网格线
        this.canvas.add(...gridLines);
        // 保存网格线引用
        this.gridLines = gridLines;
        
      } else {
        // 移除网格线
        if (this.gridLines) {
          this.gridLines.forEach(line => this.canvas.remove(line));
          this.gridLines = null;
        }
      }
      
      this.canvas.renderAll();
    },

    // 显示/隐藏标尺
    toggleRuler() {
      if (!this.canvas) return;
      
      this.showRuler = !this.showRuler;
      
      if (this.showRuler) {
        // 创建标尺
        const rulerWidth = 20;
        const interval = 100;
        const rulerColor = '#666';
        
        // 水平标尺背景
        const horizontalRuler = new fabric.Rect({
          left: rulerWidth,
          top: 0,
          width: this.canvas.width,
          height: rulerWidth,
          fill: '#f5f5f5',
          selectable: false,
          evented: false
        });
        
        // 垂直标尺背景
        const verticalRuler = new fabric.Rect({
          left: 0,
          top: rulerWidth,
          width: rulerWidth,
          height: this.canvas.height,
          fill: '#f5f5f5',
          selectable: false,
          evented: false
        });
        
        // 标尺交叉点
        const rulerCorner = new fabric.Rect({
          left: 0,
          top: 0,
          width: rulerWidth,
          height: rulerWidth,
          fill: '#e0e0e0',
          selectable: false,
          evented: false
        });
        
        // 创建刻度
        const rulerMarks = [];
        
        // 水平刻度
        for (let i = 0; i < (this.canvas.width / interval); i++) {
          const x = rulerWidth + i * interval;
          // 主刻度线
          rulerMarks.push(new fabric.Line([x, 0, x, rulerWidth], {
            stroke: rulerColor,
            strokeWidth: 1,
            selectable: false,
            evented: false
          }));
          // 刻度值
          rulerMarks.push(new fabric.Text(String(i * 100), {
            left: x + 2,
            top: 2,
            fontSize: 10,
            fill: rulerColor,
            selectable: false,
            evented: false
          }));
        }
        
        // 垂直刻度
        for (let i = 0; i < (this.canvas.height / interval); i++) {
          const y = rulerWidth + i * interval;
          // 主刻度线
          rulerMarks.push(new fabric.Line([0, y, rulerWidth, y], {
            stroke: rulerColor,
            strokeWidth: 1,
            selectable: false,
            evented: false
          }));
          // 刻度值
          rulerMarks.push(new fabric.Text(String(i * 100), {
            left: 2,
            top: y + 2,
            fontSize: 10,
            fill: rulerColor,
            selectable: false,
            evented: false,
            angle: -90
          }));
        }
        
        // 添加标尺元素
        this.canvas.add(
          horizontalRuler,
          verticalRuler,
          rulerCorner,
          ...rulerMarks
        );
        
        // 保存标尺元素引用
        this.rulerElements = [
          horizontalRuler,
          verticalRuler,
          rulerCorner,
          ...rulerMarks
        ];
        
      } else {
        // 移除标尺元素
        if (this.rulerElements) {
          this.rulerElements.forEach(element => this.canvas.remove(element));
          this.rulerElements = null;
        }
      }
      
      this.canvas.renderAll();
    },

    // 对齐到网格
    snapToGrid(target) {
      if (!this.canvas || !target) return;
      
      const gridSize = 20;
      
      const left = Math.round(target.left / gridSize) * gridSize;
      const top = Math.round(target.top / gridSize) * gridSize;
      
      target.set({
        left: left,
        top: top
      });
      
      target.setCoords();
    },

    // 显示参考线
    showGuidelines(target) {
      if (!this.canvas || !target) return;
      
      // 移除现有参考线
      this.removeGuidelines();
      
      const guidelines = [];
      const objects = this.canvas.getObjects().filter(obj => 
        obj !== target && 
        obj.type !== 'line' && 
        !obj.guidelineElement
      );
      
      objects.forEach(obj => {
        const objBounds = obj.getBoundingRect();
        const targetBounds = target.getBoundingRect();
        
        // 水平对齐
        if (Math.abs(targetBounds.top - objBounds.top) < 10) {
          guidelines.push(this.createGuideline('horizontal', objBounds.top));
        }
        if (Math.abs(targetBounds.top + targetBounds.height - objBounds.top - objBounds.height) < 10) {
          guidelines.push(this.createGuideline('horizontal', objBounds.top + objBounds.height));
        }
        
        // 垂直对齐
        if (Math.abs(targetBounds.left - objBounds.left) < 10) {
          guidelines.push(this.createGuideline('vertical', objBounds.left));
        }
        if (Math.abs(targetBounds.left + targetBounds.width - objBounds.left - objBounds.width) < 10) {
          guidelines.push(this.createGuideline('vertical', objBounds.left + objBounds.width));
        }
      });
      
      // 添加参考线
      this.canvas.add(...guidelines);
      this.guidelines = guidelines;
      
      this.canvas.renderAll();
    },

    // 创建参考线
    createGuideline(direction, position) {
      const canvasSize = direction === 'horizontal' ? this.canvas.width : this.canvas.height;
      
      return new fabric.Line(
        direction === 'horizontal' ?
          [0, position, canvasSize, position] :
          [position, 0, position, canvasSize],
        {
          stroke: '#1890ff',
          strokeWidth: 1,
          strokeDashArray: [5, 5],
          selectable: false,
          evented: false,
          guidelineElement: true
        }
      );
    },

    // 移除参考线
    removeGuidelines() {
      if (this.guidelines) {
        this.guidelines.forEach(line => this.canvas.remove(line));
        this.guidelines = null;
      }
    },

    // 显示尺寸标注
    showDimensions(target) {
      if (!this.canvas || !target) return;
      
      // 移除现有标注
      this.removeDimensions();
      
      const dimensions = [];
      const bounds = target.getBoundingRect();
      
      // 宽度标注
      dimensions.push(
        this.createDimensionLine(
          bounds.left,
          bounds.top - 20,
          bounds.left + bounds.width,
          bounds.top - 20,
          `${Math.round(bounds.width)}px`
        )
      );
      
      // 高度标注
      dimensions.push(
        this.createDimensionLine(
          bounds.left - 20,
          bounds.top,
          bounds.left - 20,
          bounds.top + bounds.height,
          `${Math.round(bounds.height)}px`,
          true
        )
      );
      
      // 添加标注
      this.canvas.add(...dimensions);
      this.dimensions = dimensions;
      
      this.canvas.renderAll();
    },

    // 创建尺寸标注线
    createDimensionLine(x1, y1, x2, y2, text, vertical = false) {
      const line = new fabric.Line([x1, y1, x2, y2], {
        stroke: '#666',
        strokeWidth: 1,
        strokeDashArray: [5, 5],
        selectable: false,
        evented: false
      });
      
      const label = new fabric.Text(text, {
        left: vertical ? x1 - 30 : (x1 + x2) / 2,
        top: vertical ? (y1 + y2) / 2 : y1 - 15,
        fontSize: 12,
        fill: '#666',
        selectable: false,
        evented: false,
        angle: vertical ? -90 : 0
      });
      
      return [line, label];
    },

    // 移除尺寸标注
    removeDimensions() {
      if (this.dimensions) {
        this.dimensions.flat().forEach(element => this.canvas.remove(element));
        this.dimensions = null;
      }
    },

    // 自动保存
    setupAutoSave() {
      // 每5分钟自动保存一次
      this.autoSaveInterval = setInterval(() => {
        if (this.canvas && this.historyStack.length > 0) {
          this.saveDesign();
        }
      }, 5 * 60 * 1000);
    },

    // 清理自动保存
    clearAutoSave() {
      if (this.autoSaveInterval) {
        clearInterval(this.autoSaveInterval);
        this.autoSaveInterval = null;
      }
    },
  },
  beforeDestroy() {
    // 清理Canvas
    if (this.canvas) {
      this.canvas.dispose();
      this.canvas = null;
    }
  }
};
</script>

<style>
.design-editor-full-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.editor-main {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 侧边栏 */
.editor-sidebar {
  width: 280px;
  background-color: #f5f5f5;
  border-right: 1px solid #e0e0e0;
  position: relative;
  transition: width 0.3s ease;
  overflow: hidden;
}

.editor-sidebar.collapsed {
  width: 40px;
  overflow: hidden;
}

.editor-sidebar.collapsed .sidebar-content {
  opacity: 0;
  visibility: hidden;
}

.sidebar-collapse-button {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-right: none;
  border-radius: 4px 0 0 4px;
  cursor: pointer;
  z-index: 10;
  font-size: 16px;
  color: #999;
}

.sidebar-collapse-button.right {
  right: auto;
  left: 0;
  border-radius: 0 4px 4px 0;
  border-right: 1px solid #e0e0e0;
  border-left: none;
}

.sidebar-collapse-button:hover {
  color: #1890ff;
}

/* 画布区域 */
.editor-canvas-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #e9e9e9;
  overflow: hidden;
  position: relative;
}

.canvas-toolbar {
  height: 40px;
  padding: 0 15px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.toolbar-left, .toolbar-center, .toolbar-right {
  display: flex;
  gap: 10px;
}

.toolbar-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  border: 1px solid #e0e0e0;
}

.tool-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.tool-button:hover {
  background-color: #f0f0f0;
  border-color: #1890ff;
}

.canvas-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #f0f0f0;
  min-height: 0;
  height: calc(100% - 40px); /* 减去工具栏高度 */
}

.canvas-box {
  position: relative;
  background: white;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  margin: 0 auto;
}

/* Canvas元素样式 */
#fabric-canvas {
  position: absolute !important;
  top: 0;
  left: 0;
  touch-action: none;
}

/* Fabric生成的Canvas容器 */
.canvas-container {
  margin: 0 !important;
  position: relative !important;
  background-color: white !important;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.debug-info {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 100;
}

/* 属性面板 */
.editor-properties {
  width: 280px;
  background-color: #f5f5f5;
  border-left: 1px solid #e0e0e0;
  overflow-y: auto;
  flex-shrink: 0;
  position: relative;
  transition: width 0.3s ease;
}

.editor-properties.collapsed {
  width: 40px;
  overflow: hidden;
}

.editor-properties.collapsed .properties-content,
.editor-properties.collapsed .properties-tabs {
  opacity: 0;
  visibility: hidden;
}

.properties-tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
  background-color: #fff;
}

.property-tab {
  flex: 1;
  padding: 12px;
  text-align: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  position: relative;
  transition: all 0.2s;
}

.property-tab:hover:not(.active) {
  color: #1890ff;
}

.property-tab.active {
  color: #1890ff;
  font-weight: 500;
}

.property-tab.active:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20%;
  width: 60%;
  height: 2px;
  background-color: #1890ff;
}

.properties-content {
  padding: 15px;
  overflow-y: auto;
  max-height: calc(100vh - 64px - 48px - 45px);
}

.property-section {
  margin-bottom: 20px;
}

.property-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
  padding-bottom: 5px;
  border-bottom: 1px solid #e0e0e0;
}

.property-group {
  background-color: #fff;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 15px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.property-group h4 {
  font-size: 14px;
  margin-bottom: 12px;
  color: #333;
}

.property-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  gap: 8px;
}

.property-row label {
  min-width: 60px;
  font-size: 12px;
  color: #666;
}

.property-row input[type="number"],
.property-row input[type="text"],
.property-row select {
  flex: 1;
  height: 32px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
}

.property-row textarea {
  width: 100%;
  min-height: 60px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 8px;
  font-size: 14px;
  resize: vertical;
}

.property-row input[type="range"] {
  flex: 1;
}

.property-row input[type="color"] {
  height: 32px;
  width: 32px;
}

/* 按钮样式 */
.style-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.style-button:hover {
  border-color: #1890ff;
}

.font-bold {
  font-weight: bold;
}

.font-italic {
  font-style: italic;
}

.font-underline {
  text-decoration: underline;
}

/* 文本样式预览 */
.heading {
  font-size: 24px;
  font-weight: bold;
}

.subheading {
  font-size: 18px;
}

.paragraph {
  font-size: 14px;
}

.editor-toolbar {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  gap: 4px;
  height: 50px;
}

.toolbar-group {
  display: flex;
  align-items: center;
  gap: 2px;
  padding: 0 4px;
  position: relative;

  &:not(:last-child)::after {
    content: '';
  position: absolute;
    right: 0;
    top: 4px;
    bottom: 4px;
    width: 1px;
    background: #e8e8e8;
  }
}

.toolbar-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border: 1px solid transparent;
  border-radius: 4px;
  background: transparent;
  color: #595959;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;

  &:hover {
    background: #f5f5f5;
    border-color: #d9d9d9;
    color: #1890ff;
  }

  &:active {
    background: #e6f7ff;
    border-color: #1890ff;
    color: #1890ff;
  }

  &.active {
    background: #e6f7ff;
    border-color: #1890ff;
    color: #1890ff;
  }

  &.danger {
    &:hover {
      background: #fff1f0;
      border-color: #ffa39e;
      color: #ff4d4f;
    }
    
    &:active {
      background: #fff1f0;
      border-color: #ff4d4f;
      color: #ff4d4f;
    }
  }

  i {
    font-size: 14px;
  }
}

.toolbar-separator {
  width: 1px;
  height: 24px;
  background: #e8e8e8;
  margin: 0 4px;
}

.zoom-level {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 60px;
  height: 36px;
  padding: 0 8px;
  font-size: 13px;
  color: #595959;
  background: #f5f5f5;
  border-radius: 4px;
  user-select: none;
}

.group-separator {
  width: 1px;
  height: 24px;
  background-color: #ddd;
  margin: 0 8px;
}

.zoom-level {
  min-width: 48px;
  text-align: center;
  font-size: 12px;
  color: #666;
  user-select: none;
}
</style> 